package com.thinkgem.jeesite.modules.quartz;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.modules.de.entity.AttendanceDe;
import com.thinkgem.jeesite.modules.de.service.AttendanceDeService;

@Service("fileProcessDEJob")
public class FileProcessDEJob {

	// 原始目录
	public final String deSrcDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("deSrcDirName");
	// 中转目录
	public final String deTransferDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("deTransferDirName");
	// 中转目录,真是存放文件地址
	public final String deTransferDirName2 = Global.getUserfilesBaseDir()
			+ Global.getConfig("deTransferDirName2");
	// 备份目录
	public final String deBackupsDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("deBackupsDirName");
	/**
	 * 日志
	 */
	private static final Log log = LogFactory.getLog(FileProcessDEJob.class);

	@Autowired
	private AttendanceDeService attendanceDeService;

	 public static void main(String[] args) {
	 new FileProcessDEJob().importFile("E:\\winit\\打卡考勤\\德国\\DE 2016.09.pdf");
	 }

	/**
	 * 定时任务拷贝及处理文件.
	 */
	public void doSomeThing() {
		try {

			// copy文件到指定中专目录
			boolean result = FileUtils.copyDirectoryCover(deSrcDirName,
					deTransferDirName, true);
			if (result) {
				// 删除上传过的原文件
				FileUtils.deleteDirectory2(deSrcDirName);
			} else {
				return;
			}

			// 解析文件，把数据放到数据库
			// 列出源目录下的所有文件名和子目录名
			File srcDir = new File(deTransferDirName2);
			File[] files = srcDir.listFiles();
			if (files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].isFile()) {
						String fileName = files[i].getAbsolutePath();
						// 如果是一个单个文件，则直接复制
						importFile(fileName);
						String newFileName = deBackupsDirName
								+ files[i].getName();
						// 拷贝文件
						boolean flag = FileUtils.copyFileCover(fileName,
								newFileName, true);
						if (flag) {
							// 删除原始文件
							FileUtils.deleteFile(fileName);
						}
					}
				}
			}
			log.info("德国测试定时任务..............................");
			System.out.println("德国测试定时任务..............................");
		} catch (Exception e) {
			log.error("德国正岗定时任务拷贝及处理文件错误" + e.getMessage(), e);
			e.printStackTrace();
		}

	}

	/**
	 * 在字符串中，查找对应字符
	 * 
	 * @param str
	 * @param findstr
	 * @return
	 */
	public boolean indexof(String str, String findstr) {
		if (null == str || str.length() < 0) {
			return false;
		}

		if (null == findstr || findstr.length() < 0) {
			return false;
		}

		int result = str.indexOf(findstr);
		// 查找标记，true表示在字符串中找到findstr，false表示在字符串中找不到findstr
		if (result >= 0) {
			return true;
		}
		return false;
	}

	/**
	 * 数据库保存数据.
	 * 
	 * @param fileName
	 */
	public void importFile(String fileName) {
		File pdfFile = new File(fileName);
		// //获取解析后得到的PDF文档对象
		PDDocument document = null;
		BufferedReader in = null;
		try {
			// 加载文件：
			document = PDDocument.load(pdfFile);
			// 获取页码
			int pages = document.getNumberOfPages();
			// 新建一个PDF文本剥离器
			PDFTextStripper stripper = new PDFTextStripper();
			// 设置按顺序输出
			stripper.setSortByPosition(true);
			stripper.setStartPage(1);
			stripper.setEndPage(pages);
			// 从PDF文档对象中剥离文本
			String content = stripper.getText(document);
			in = new BufferedReader(new StringReader(content));
			String str = new String();
			String heaDdatum = null;
			String datumYear = null;
			String name = null;
			String id = null;
			String dienstplan = null;
			String abteilung = null;
			// 循环读取数据
			while ((str = in.readLine()) != null) {
				boolean flagDat = indexof(str, "Datum:");
				boolean flagMontag = indexof(str, "Montag");
				boolean flagBemerkung = indexof(str, "Bemerkung");
				boolean flagName = indexof(str, "Name:");
				boolean flagAb = indexof(str, "Abteilung:");
				boolean flagMo = indexof(str, "Mo");
				boolean flagDi = indexof(str, "Di");
				boolean flagMi = indexof(str, "Mi");
				boolean flagDo = indexof(str, "Do");
				boolean flagFr = indexof(str, "Fr");
				boolean flagSa = indexof(str, "Sa");
				boolean flagSo = indexof(str, "So");
				if (flagBemerkung) {

					continue;
				} else if (flagMontag) {// 分页标记
					continue;
				} else if (flagDat) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						heaDdatum = strArray[1];
						datumYear = strArray[3].substring(6,
								strArray[3].length());
					}
					continue;
				} else if (flagName) {
					name = str.substring(5, str.indexOf("ID"));
					id = str.substring(str.indexOf("ID") + 3,
							str.indexOf("Dienstplan")).trim();
					dienstplan = str.substring(str.indexOf("Dienstplan") + 11,
							str.length());	
					continue;
				} else if (flagAb) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						abteilung = strArray[1];
					}
					continue;
				} else if (flagMo) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}

				} else if (flagDi) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}
				} else if (flagMi) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}
				} else if (flagDo) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}
				} else if (flagFr) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}
				} else if (flagSa) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}
				} else if (flagSo) {
					String[] strArray = str.split(" ");
					if (strArray.length >= 0) {
						AttendanceDe de = setBean(heaDdatum, datumYear, name,
								id, dienstplan, abteilung, strArray);
						if (null != de) {
							attendanceDeService.save(de);
						}
						continue;
					}// end if
				}// end else if

			}// end while

		} catch (Exception e) {
			log.error("德国正岗定时任务解析文件处理数据错误" + e.getMessage(), e);
			e.printStackTrace();
			return;
		} finally {
			// 关闭文件流
			if (null != document) {
				try {
					// 关闭文件流程
					document.close();
				} catch (IOException e) {
					log.error("关闭文件流[PDDocument]错误" + e.getMessage(), e);
					// TODO Auto-generated catch block
					e.printStackTrace();
					return;
				}
			}

			// 关闭文件流
			if (null != in) {
				try {
					// 关闭文件流程
					in.close();
				} catch (IOException e) {
					log.error("关闭文件流[BufferedReader]错误" + e.getMessage(), e);
					// TODO Auto-generated catch block
					e.printStackTrace();
					return;
				}
			}
		}
	}

	/**
	 * 对象转换.
	 * 
	 * @param headDatum
	 * @param datumYear
	 * @param name
	 * @param id
	 * @param dienstplan
	 * @param abteilung
	 * @param strArray
	 * @return
	 */
	public AttendanceDe setBean(String headDatum, String datumYear,
			String name, String id, String dienstplan, String abteilung,
			String[] strArray) {
		AttendanceDe de = new AttendanceDe();
		de.setHeadDatum(headDatum);
		de.setName(name);
		de.setEmployeeId(id);
		de.setDienstplan(dienstplan);
		de.setAbteilung(abteilung);
		if (strArray.length >= 0) {

			try {
				if ("nstag,".equals(strArray[0].substring(3,
						strArray[0].length()))) {
					return null;
				}
				String str = datumYear + "-"
						+ strArray[0].substring(3, strArray[0].length()) + "-"
						+ strArray[0].substring(0, 2);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdf.parse(str);
				de.setDatum(date);
				//PDF 排除的三个字段：Krank 、Urlaub、Feiertag 备注出现以上三个字段的工时剔除，除此之外的所有工时应保留
				if (indexof(strArray[strArray.length - 1].trim(),"Krank")
						|| indexof(strArray[strArray.length - 1].trim(),"Urlaub")
						|| indexof(strArray[strArray.length - 1].trim(),"Feiertag")) {
					return null;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.error("日期转换错误[ParseException]错误" + e.getMessage(), e);
				return null;
			}
		}
		if (strArray.length >= 1) {
			de.setTag(strArray[1]);
		}
		// 计算工时
		if (strArray.length >= 5) {
			if (strArray[5].indexOf(":") > -1) {
				String[] ab = strArray[5].split(":");
				Double a = Double.parseDouble(ab[0]);
				Double b = Double.parseDouble(ab[1]) / 60;// 分钟转换成小时
				Double abSum = a + b;
				if(abSum <=0)
				{
					return null;
				}
				de.setStunden(String.valueOf(abSum));
			}
		}

		if (strArray.length >= 7) {
			de.setCumm(strArray[7]);
		}
		return de;
	}
}
